import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'
import { Script, CreateScriptData, UpdateScriptData } from '@/types/script'
import * as scriptAPI from '@/services/scriptAPI'

interface ScriptState {
  scripts: Script[]
  currentScript: Script | null
  loading: boolean
  error: string | null
  searchKeyword: string
  selectedTags: string[]
  currentFolderId: string | null
}

const initialState: ScriptState = {
  scripts: [],
  currentScript: null,
  loading: false,
  error: null,
  searchKeyword: '',
  selectedTags: [],
  currentFolderId: null,
}

// 异步thunks
export const fetchScripts = createAsyncThunk(
  'script/fetchScripts',
  async (params?: {
    keyword?: string
    tags?: string[]
    folderId?: string
    limit?: number
    offset?: number
  }) => {
    const response = await scriptAPI.getScripts(params)
    return response.data
  }
)

export const createScript = createAsyncThunk(
  'script/createScript',
  async (scriptData: CreateScriptData) => {
    const response = await scriptAPI.createScript(scriptData)
    return response.data
  }
)

export const updateScript = createAsyncThunk(
  'script/updateScript',
  async ({ id, data }: { id: string; data: UpdateScriptData }) => {
    const response = await scriptAPI.updateScript(id, data)
    return response.data
  }
)

export const deleteScript = createAsyncThunk(
  'script/deleteScript',
  async (id: string) => {
    await scriptAPI.deleteScript(id)
    return id
  }
)

export const fetchScriptById = createAsyncThunk(
  'script/fetchScriptById',
  async (id: string) => {
    const response = await scriptAPI.getScript(id)
    return response.data
  }
)

const scriptSlice = createSlice({
  name: 'script',
  initialState,
  reducers: {
    setCurrentScript: (state, action: PayloadAction<Script | null>) => {
      state.currentScript = action.payload
    },
    setSearchKeyword: (state, action: PayloadAction<string>) => {
      state.searchKeyword = action.payload
    },
    setSelectedTags: (state, action: PayloadAction<string[]>) => {
      state.selectedTags = action.payload
    },
    setCurrentFolderId: (state, action: PayloadAction<string | null>) => {
      state.currentFolderId = action.payload
    },
    clearError: (state) => {
      state.error = null
    },
  },
  extraReducers: (builder) => {
    builder
      // fetchScripts
      .addCase(fetchScripts.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchScripts.fulfilled, (state, action) => {
        state.loading = false
        state.scripts = action.payload.scripts || []
      })
      .addCase(fetchScripts.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message || '获取脚本列表失败'
      })
      // createScript
      .addCase(createScript.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(createScript.fulfilled, (state, action) => {
        state.loading = false
        state.scripts.unshift(action.payload)
        state.currentScript = action.payload
      })
      .addCase(createScript.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message || '创建脚本失败'
      })
      // updateScript
      .addCase(updateScript.fulfilled, (state, action) => {
        const index = state.scripts.findIndex(s => s.id === action.payload.id)
        if (index !== -1) {
          state.scripts[index] = action.payload
        }
        if (state.currentScript?.id === action.payload.id) {
          state.currentScript = action.payload
        }
      })
      // deleteScript
      .addCase(deleteScript.fulfilled, (state, action) => {
        state.scripts = state.scripts.filter(s => s.id !== action.payload)
        if (state.currentScript?.id === action.payload) {
          state.currentScript = null
        }
      })
      // fetchScriptById
      .addCase(fetchScriptById.fulfilled, (state, action) => {
        state.currentScript = action.payload
      })
  },
})

export const {
  setCurrentScript,
  setSearchKeyword,
  setSelectedTags,
  setCurrentFolderId,
  clearError,
} = scriptSlice.actions

export default scriptSlice.reducer